# ~*~ coding: utf-8 ~*~
import json
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import InputRequired

from apps.common.form import ErrorFormMinx

__all__ = ['PeriodicTaskForm']


class PeriodicTaskForm(ErrorFormMinx, FlaskForm):
    name = StringField(validators=[InputRequired(message="任务名称不能为空")])
    function_id = StringField(validators=[InputRequired(message="任务函数不能为空")])
    interval_id = StringField()
    crontab_id = StringField()
    args = StringField()
    kwargs = StringField()
    enabled = StringField()
    only_once = StringField()
    description = StringField()

    def validate(self):
        if not super().validate():
            return False

        interval = self.interval_id.data
        crontab = self.crontab_id.data

        if not interval and not crontab:
            self.update_error(
                {
                    'global': ['必须选择一种调度类型']
                }
            )
            return False

        if interval and crontab:
            self.update_error(
                {
                    'global': ['必须选择一种调度类型']
                }
            )
            return False

        return True

    @property
    def data(self):
        args = json.loads(self.args.data)
        kwargs = json.loads(self.kwargs.data)
        return {
            'name': self.name.data.strip(),
            'function_id': self.function_id.data.strip(),
            'interval_id': self.interval_id.data.strip(),
            'crontab_id': self.crontab_id.data.strip(),
            'args': [arg.strip() for arg in args],
            'kwargs': {k.strip(): v.strip() for k, v in kwargs.items()},
            'enabled': True if int(self.enabled.data) else False,
            'only_once': True if int(self.only_once.data) else False,
            'description': self.description.data.strip(),
        }
